<script setup>
import {watch} from "vue";

const props = defineProps({
  modelValue: {
    type: Number,
    default: 30 * 60 * 1000 // 毫秒
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:modelValue'])

const selectedDays = ref(0)
const selectedHours = ref(0)
const selectedMinutes = ref(30)

const days = Array.from(Array(31).keys())
const hours = Array.from(Array(24).keys())
const minutes = [0, 10, 20, 30, 40, 50]

const maxMinutes = 30 * 24 * 60

const updateDuration = (type) => {
  if (type === 'day') {
    selectedMinutes.value = 0
    selectedHours.value = 0
  }
  if (type === 'hour') selectedMinutes.value = 0
  if (['hour', 'minuted'].includes(type)) {
    if ((selectedMinutes.value > 0 || selectedHours.value) > 0 && selectedDays.value > 29) selectedDays.value = 29
  }
  const totalMinutes =
    parseInt(selectedDays.value) * 24 * 60 +
    parseInt(selectedHours.value) * 60 +
    parseInt(selectedMinutes.value);
  emits("update:modelValue", totalMinutes * 60 * 1000);
};

const setInitialValues = () => {
  let remainingMinutes = Math.round(props.modelValue / 60 / 1000);
  selectedDays.value = Math.floor(remainingMinutes / (24 * 60));
  remainingMinutes -= selectedDays.value * 24 * 60;
  selectedHours.value = Math.floor(remainingMinutes / 60);
  remainingMinutes -= selectedHours.value * 60;
  selectedMinutes.value = remainingMinutes;
};

watch(() => props.modelValue, () => {
  setInitialValues();
}, {
  immediate: true
})

</script>

<template>
  <div class="time-length-box">
    <div class="item">
      <el-select class="select" v-model="selectedDays" :disabled="disabled" placeholder="天" @change="updateDuration('day')">
        <el-option v-for="day in days" :key="day" :label="day" :value="day"/>
      </el-select>
      <span>天</span>
    </div>
    <div class="item">
      <el-select class="select" v-model="selectedHours" :disabled="disabled" placeholder="时" @change="updateDuration('hour')">
        <el-option v-for="hour in hours" :key="hour" :label="hour" :value="hour"
                   :disabled="(selectedDays * 24 + hour) * 60 > maxMinutes"/>
      </el-select>
      <span>时</span>
    </div>
    <div class="item">
      <el-select class="select" v-model="selectedMinutes" :disabled="disabled" placeholder="分" @change="updateDuration('minute')">
        <el-option v-for="minute in minutes" :key="minute" :label="minute" :value="minute"
                   :disabled="(selectedDays * 24 * 60 + selectedHours * 60 + minute) > maxMinutes"/>
      </el-select>
      <span>分</span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.time-length-box {
  display: flex;
  align-items: center;

  > .item {
    display: flex;
    align-items: center;
    margin-right: 15px;

    .select {
      width: 60px;
      margin-right: 5px;
    }
  }
}
</style>
